require("./config/global_config")
require("./hg/server.js")
require("./http_server.js")
const websocket = require("./websocket")
const Controller = require("./controller")
const PS3838Client = require("./ps3838api")
const Titan007 = require("./titan007.js")
const websocketOrder = require("./websocket_order")
// 全局变量：用 Map 保存全部最新数据
const latestMergedMap = new Map();
const controller = new Controller()
const titan007 = new Titan007()

const client1 = new PS3838Client({
    username: 'ga34204006',
    password: 'wwss2233'
});

const client2 = new PS3838Client({
    username: 'GA34204ZZ3',
    password: 'wwss2233'
});






function main() {
    websocket.create(controller)
    websocketOrder.create()
    // 创建 Titan007 的 WebSocket 连接
    // titan007.createWS()
    loop()
}
global.PS_OPEN_HAND = false

async function loop() {
    let balance = await orderClient.getBalance() // 获取余额，验证登录
    global.log(`PS3838 订单账号余额：${balance}`)
    let lastUpdatTime = 0;
    let sportId = 29;
    let lastEventsMap = new Map(); // 用 Map 去重（key = eventId）
    let client1Req = true;
    let lastUpdteFixtureTime = 0;

    while (true) {
        if (global.PS_OPEN || global.PS_OPEN_HAND) {
            if (lastUpdatTime > 0) {
                console.info(`PS轮询间隔：${(Date.now() - lastUpdatTime) / 1000}`);
            }
            let client = client1Req ? client1 : client2;
            client1Req = !client1Req; // 切换客户端
            let fixturesData;
            // 如果当前时间距离上次获取 fixtures 的时间超过 1 分钟，则获取 全部fixtures
            if (Date.now() - lastUpdteFixtureTime > 60 * 1000) {
                fixturesData = await client.getFixtures({ sportId, isLive: 1 }, true);
                lastEventsMap = new Map();
                lastUpdteFixtureTime = Date.now();// 记录上次获取 fixtures 的时间
            } else {
                fixturesData = await client.getFixtures({ sportId, isLive: 1 });
            }
            if (fixturesData === false) {
                console.error('获取 fixtures 失败，跳过本次循环');
                await sleep(60000 * 5); // 等待 5 秒后重试
                continue;
            }
            let liveGames = await client.parseLiveEvents(fixturesData);
            if (liveGames.length > 0) {
                // 使用 Map 去重，更新最新的 live 数据
                for (const g of liveGames) {
                    lastEventsMap.set(g.eventId, g);
                }
            }
            // 将 Map 转成数组
            const liveEvents = Array.from(lastEventsMap.values());
            console.info(`PS比赛数量：${liveEvents.length}`);
            const eventIds = liveEvents.map(g => g.eventId);
            const oddsData = await client.getOdds({ sportId, eventIds });
            const merged = await client.mergeFixturesWithOdds(liveEvents, oddsData);

            if (merged.length > 0) {
                for (const item of merged) {
                    latestMergedMap.set(item.id, item); // 更新或新增
                }
                controller.setData(latestMergedMap)
                client.lastData = latestMergedMap
                controller.FULL_DATA()
            }
            lastUpdatTime = Date.now();
        }
        await sleep(2500); // 暂停 2.5 秒再继续
    }
}


function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}


main()

